﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[AddComponentMenu("Behavior/SpriteIndex")]
[ExecuteInEditMode]
public class BhvSpriteIndex : MonoBehaviour
{

    public Sprite[] sprites;

    private SpriteRenderer spriteRenderer;
    private void Awake()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();
        UpdateFromIndex(this.index);
    }

    [SerializeField]
    private int _index;
    public int index
    {
        get
        {
            return _index;
        }
        set
        {
            if (value > sprites.Length - 1) value = sprites.Length - 1;
            if (value < 0) value = 0;
            UpdateFromIndex(value);
            _index = value;
        }
    }
#if UNITY_EDITOR
    bool _dirty = false;
    private void OnValidate()
    {
        if (sprites == null || sprites.Length <= 0) return;
        if (_index > sprites.Length - 1) _index = sprites.Length - 1;
        if (_index < 0) _index = 0;
        _dirty = true;
    }


    private void Update()
    {
        if (_dirty)
        {
            _dirty = false;
            UpdateFromIndex(_index);
        }
    }

#endif


    private void UpdateFromIndex(int value)
    {
        if (!spriteRenderer)
        {
            spriteRenderer = GetComponent<SpriteRenderer>();
            if (spriteRenderer == null) return;
        }
        if (sprites.Length == 0) return;
        if (sprites.Length >= value && sprites[value])
        {
            spriteRenderer.sprite = sprites[value];
        }
        else
        {
            spriteRenderer.sprite = null;
        }
    }


}
